const express = require('express')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const admzip = require('adm-zip')

const app = express()
const router = express.Router()
app.use(router)

app.use('/public', express.static(path.join(__dirname, 'public')));

app.set('views', path.join(__dirname, 'views'));
// app.engine('html', require('ejs').renderFile)
app.set('view engine', 'ejs');

router.get('/shuai', function (req, res, next) {
  res.render('index')
})

const upload = multer({
  dest: path.join(__dirname, 'public/upload/')
});

router.post('/shuai/upload', upload.single('upload_file'), function (req, res) {
  var temp_path = req.file.path;
  var _namearr = req.file.originalname.split('.');
  var ext = '.' + _namearr[_namearr.length - 1];
  var target_path = req.file.path + ext;
  var _filename = req.file.filename + ext;
  var filePath = '/upload/' + _filename;
  fs.rename(temp_path, target_path, function (err, data) {

    let zip = new admzip('./public' + filePath)
    let tempPath = './public/temp' + Date.now()
    let strobj = ''
    zip.extractAllToAsync(tempPath, true, function () {

      let path = tempPath + '/word/document.xml'
      let data = fs.readFileSync(path, 'utf-8')

      let dirpath = tempPath + '/word/media/'
      if (fs.existsSync(dirpath)) {

        let dir = fs.readdirSync(dirpath)

        let _todir = '/public/wordimg/'

        let fileArr = []
        dir.forEach(function (item, index) {
          fs.stat(dirpath + item, function (err, stats) {
            if (stats.isFile()) {
              let _namearr = item.split('.')
              let _ext = _namearr[_namearr.length - 1]
              let _newname = 'wordimg-' + Date.now()
              fileArr.push(_todir + _newname + '.' + _ext)
              fs.copyFileSync(dirpath + item, '.' + _todir + _newname + '.' + _ext)

              console.log(index, dir.length - 1)
              if (index == dir.length - 1) {

                let allcont = ''
                data.match(/(<w:p>[\s\S]*?<\/w:p>)/ig).forEach(item => {
                  allcont += item.replace(/(w:p)/ig, 'p')
                })

                if (fileArr.length > 0) {
                  for (let i = 0; i < fileArr.length; i++) {
                    allcont = allcont.replace(/(<w:drawing>[\s\S]*?<\/w:drawing>)/i, "<img src='http://localhost:3002" + fileArr[i] + "' />")
                  }
                }

                allcont = allcont.replace(/(<w:t>)|(<\/w:t>)/ig, '')
                allcont = allcont.replace(/(<w.*?>).*?(<\/w.*?>)/ig, '')

                rmdir(tempPath, () => {
                  console.log('文件删除完毕')
                })

                res.render('result', {
                  data: allcont
                })
              }
            }
          })
        })
      } else {
        let allcont = ''
        data.match(/(<w:p>[\s\S]*?<\/w:p>)/ig).forEach(item => {
          allcont += '<p>' + item.replace(/(<.*?>)/ig, '') + '</p>'
        })

        rmdir(tempPath, () => {
          console.log('文件删除完毕')
        })

        res.render('result', {
          data: allcont
        })
      }
    })
  });
});


function rmdir(dir, callback) {
  fs.readdir(dir, (err, files) => {
    /**
     * @desc 内部循环遍历使用的工具函数
     * @param {Number} index 表示读取files的下标
     */
    function next(index) {
      // 如果index 等于当前files的时候说明循环遍历已经完毕，可以删除dir，并且调用callback
      if (index == files.length) return fs.rmdir(dir, callback)
      // 如果文件还没有遍历结束的话，继续拼接新路径，使用fs.stat读取该路径
      let newPath = path.join(dir, files[index])
      // 读取文件，判断是文件还是文件目录

      fs.stat(newPath, (err, stat) => {
        if (stat.isDirectory()) {
          // 因为我们这里是深度循环，也就是说遍历玩files[index]的目录以后，才会去遍历files[index+1]
          // 所以在这里直接继续调用rmdir，然后把循环下一个文件的调用放在当前调用的callback中
          rmdir(newPath, () => next(index + 1))
        } else {
          // 如果是文件，则直接删除该文件，然后在回调函数中调用遍历nextf方法，并且index+1传进去
          fs.unlink(newPath, () => next(index + 1))
        }
      })
    }
    next(0)
  })
}

app.listen(3002, function () {
  console.log('listen 3002')
})